import React, { Fragment, useCallback, useContext, useEffect } from 'react';
import { Drawer, Button, Space, Form, Badge } from 'antd';
import { FilterOutlined, ClearOutlined, MinusCircleOutlined } from '@ant-design/icons';
import '../../styles.less';
import cls from 'classnames';
import { ManageContext } from '../../store/index';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { SearchComponent } from '../SearchComponent';
import { handleFilterPayload } from '../../hooks/useHandleDeptValues';
import _ from 'lodash';
export interface IFilterDrawer {
  visible: boolean;
  onClose: any;
  searchDrawerRender?: string | null | undefined;
  filterInitValue: Record<string, any>;
}

export const FilterDrawer: React.FC<IFilterDrawer> = ({ visible, onClose, searchDrawerRender, filterInitValue }) => {
  const { Search } = useContext(ManageContext);

  const [form] = Form.useForm();

  useEffect(() => {
    if (visible) {
      if (Object?.keys(Search?.filterDrawerValues).length > 0) {
        form.resetFields();
        const searchFormList: Record<string, any> = _.cloneDeep(Search?.filterDrawerValues);
        Object.keys(Search?.filterDrawerValues)?.forEach((item: any) => {
          if (item?.includes('FormNameDept')) {
            const formDeptDefault: string[] = searchFormList?.[item]?.map((itemDept: any) => {
              return itemDept?.value;
            });
            searchFormList[item] = formDeptDefault;
          }
        });
        form.setFieldsValue({
          ...searchFormList,
        });
      } else {
        form.resetFields();
      }
    }
  }, [Search?.filterDrawerValues, visible]);

  useEffect(() => {
    form?.setFieldsValue({
      ...filterInitValue,
    });
    Search.saveFilterValues(filterInitValue);
  }, [filterInitValue]);

  const onFilter = () => {
    form.resetFields();
    Search.saveFilterValues({});
  };

  const onFormValuesChange = (target: any, allValues: any) => {
    const filterValues: any = {};
    let orgFormList = handleFilterPayload(target, Search.searchList);
    let newAllValues = {
      ...Search?.filterDrawerValues,
      ...allValues,
      ...orgFormList,
    };
    Object?.keys(newAllValues)?.forEach((i) => {
      if (newAllValues[i] || newAllValues[i] >= 0) {
        if (!(Array?.isArray(newAllValues[i]) && newAllValues[i]?.length == 0)) {
          filterValues[`${i}`] = newAllValues[i];
        }
      }
    });
    Search.saveFilterValues(filterValues);
  };

  const footer = (
    <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
      <Space>
        <Button onClick={onClose} icon={<MinusCircleOutlined />}>
          关闭
        </Button>
        <Button type="primary" icon={<ClearOutlined />} onClick={onFilter}>
          清除
        </Button>
      </Space>
    </div>
  );

  return (
    <Drawer
      open={visible}
      // title={
      //   <div className={cls('filter-drawer-title')}>
      //     <Badge.Ribbon
      //       text={
      //         <>
      //           <FilterOutlined style={{ marginRight: '8px' }} />
      //           <span>更多筛选</span>
      //         </>
      //       }
      //       placement="end"
      //     />
      //   </div>
      // }
      placement="right"
      closable={false}
      getContainer={searchDrawerRender ? (document.getElementById(searchDrawerRender) as any) : false}
      style={{ position: 'absolute' }}
      width={document.body.clientWidth * 0.3}
      onClose={onClose}
      headerStyle={{
        padding: '8px',
      }}
      closeIcon
      footer={footer}
      bodyStyle={{
        padding: 0,
        overflowX: 'hidden',
        overflowY: 'auto',
      }}
      className={cls('filter-drawer')}
    >
      <ScrollBarLayout
        style={{
          padding: '1rem',
        }}
      >
        <Form layout="vertical" form={form} onValuesChange={onFormValuesChange}>
          {(visible || filterInitValue) && (
            <>
              {Search?.searchList &&
                Search?.searchList?.map((item: any, index: number) => {
                  if (item?.whetherSenior) {
                    if (
                      item?.componentType == 'DeptAndUser' || //部门岗位
                      item?.componentType == 'NumberRange' //数量范围
                    ) {
                      return (
                        <Fragment key={index + 'filter'}>
                          <SearchComponent opt={{ ...item, searchForm: form }} type={item?.componentType} visible={visible} />
                        </Fragment>
                      );
                    } else {
                      return (
                        <Form.Item
                          style={{ ...item?.itemStyle }}
                          name={item?.name}
                          label={item?.label}
                          className={cls('drawer-form-item')}
                          key={index}
                          initialValue={item?.initialValue || undefined}
                        >
                          <SearchComponent type={item?.componentType} opt={{ ...item, searchForm: form }} />
                        </Form.Item>
                      );
                    }
                  }
                })}
            </>
          )}
        </Form>
      </ScrollBarLayout>
    </Drawer>
  );
};
